<?php

namespace System\Configure\Adapter;

use Exception;
use System\Configure\AdapterAbstract;
use System\Configure\Exception\ParserPhpException;
use System\Configure\Exception\ParserPhpNotArrayException;

/**
 * PHP配置文件解析类
 *
 * @package Dream
 * @subpackage Php
 * @namespace System\Configure\Adapter
 * @author lewis (lewisld@yeah.net)
 */
class Php extends AdapterAbstract
{

    /**
     * PHP配置文件解析后的数组
     *
     * @static
     * @access protected
     * @var array
     */
    protected static $data = [];

    /**
     * 解析PHP配置文件
     * 加载一个PHP文件,其内容是一个数组
     *
     * @static
     * @param string $path PHP配置文件路径
     * @return array 返回配置数组
     * @throws ParserPhpException 解析INI配置文件到数组异常
     * @throws ParserPhpNotArrayException 解析PHP配置文件返回非数组异常
     */
    public static function parser($path)
    {
        try {
            self::$data = require $path;
        } catch (Exception $e) {
            $error = [
                'message' => 'system.error.conf.parser.php',
                'exception' => $e,
                'phpfile' => $path
            ];
            throw new ParserPhpException($error);
        }
        if (is_callable(self::$data)) {
            $this->data = call_user_func(self::$data);
        }
        if (! self::$data || ! is_array(self::$data)) {
            throw new ParserPhpNotArrayException([
                'system.error.conf.parser.php.not.array',
                [
                    'file' => $path
                ]
            ]);
        }
        return self::$data;
    }
}
